<?php
/**
 * Created by PhpStorm.
 * User: LuLingFeng
 * Date: 2017/12/27
 * Time: 13:20
 */
namespace App\Http\Admin\Personnel\Controllers;

use App\Eloquent\Oa\Log\BusinessTrip;
use App\Eloquent\Oa\Log\Leave;
use App\Eloquent\Oa\Log\Overtime;
use App\Http\Admin\Administration\Models\Flow;
use App\Http\Admin\Personnel\Models\Attendance;
use App\Http\Admin\Personnel\Models\AttendanceFactor;
use App\Http\Admin\Personnel\Models\AttendanceLog;
use Carbon\Carbon;
use Framework\BaseClass\Http\Admin\Controller;

class AttendanceController extends Controller
{
    public function statisticsCount()
    {
        $companyId = session('current_operation_company_id');
        if (!$companyId) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $where = $this->getRequestParameters([], ['start_time', 'end_time']);
        $where['oa_company_id'] = $companyId;
        $manager = new Attendance();
        $data = $manager->statisticsCount($where)->toArray()[0];
        return $data;
    }

    public function statisticsListPage()
    {
        $yesterday = Carbon::yesterday();
        $companyId = session('current_operation_company_id');
        if (!$companyId) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $data = [
            'max_time'      => $yesterday->format('Y-m-d'),
            'end_time'      => $yesterday->format('Y-m-d'),
            'start_time'    => $yesterday->firstOfMonth()->format('Y-m-d'),
            'oa_company_id' => $companyId
        ];
        $manager = new Attendance();
        $data = array_merge($data, $manager->statisticsCount($data)->toArray()[0]);
        return $this->view('statistics-list', $data);
    }

    public function statisticsList()
    {
        $companyId = session('current_operation_company_id');
        if (!$companyId) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $where = $this->getRequestParameters([], ['name', 'start_time', 'end_time']);
        $where['company_id'] = $companyId;
        $paging = $this->getPagingRequestParameters();
        $manager = new Attendance();
        $data = $manager->statisticsList($where, $paging);

        $fm = new AttendanceFactor();
        $leaveStat = $fm->commonStat(Leave::with([]), [
            'oa_company_id' => $companyId,
            'start_time'    => $where['start_time'],
            'end_time'      => $where['end_time']
        ], 'oa_contacts_id', [\DB::raw('count(1) as total, oa_contacts_id')]);
        $leaveRecord = [];
        foreach ($leaveStat as $item) $leaveRecord[$item['oa_contacts_id']] = $item['total'];
        $btStat = $fm->commonStat(BusinessTrip::with([]), [
            'oa_company_id' => $companyId,
            'start_time'    => $where['start_time'],
            'end_time'      => $where['end_time']
        ], 'oa_contacts_id', [\DB::raw('count(1) as total, oa_contacts_id')]);
        $btRecord = [];
        foreach ($btStat as $item) $btRecord[$item['oa_contacts_id']] = $item['total'];
        $overtimeStat = $fm->commonStat(Overtime::with([]), [
            'oa_company_id' => $companyId,
            'start_time'    => $where['start_time'],
            'end_time'      => $where['end_time']
        ], 'oa_contacts_id', [\DB::raw('count(1) as total, oa_contacts_id')]);
        $overtimeRecord = [];
        foreach ($overtimeStat as $item) $overtimeRecord[$item['oa_contacts_id']] = $item['total'];

        foreach ($data['list'] as $item) {
            $item['leave_times'] = isset($leaveRecord[$item['oa_contacts_id']]) ? $leaveRecord[$item['oa_contacts_id']] : 0;
            $item['business_trip_times'] = isset($btRecord[$item['oa_contacts_id']]) ? $btRecord[$item['oa_contacts_id']] : 0;
            $item['overtime_times'] = isset($overtimeRecord[$item['oa_contacts_id']]) ? $overtimeRecord[$item['oa_contacts_id']] : 0;
        }

        return $data;
    }

    public function statisticsCheckInLogPage()
    {
        $data = request(['oa_contacts_id', 'start_time', 'end_time', 'result_type', 'check_in_type']);
        return $this->view('statistics-check-in-log', $data);
    }

    public function logList()
    {
        $type = request('list_type');
        $where = request([
            'oa_contacts_id', 'oa_department_id', 'oa_company_id', 'relate_id',
            'type', 'result_type', 'check_in_type', 'start_time', 'end_time'
            ]);
        $paging = $this->getPagingRequestParameters();
        $log = new AttendanceLog();
//        $manager = new Attendance();
        switch ($type) {
            case 'statistics-check-in-log':
                $data = $log->logList($where, $paging, ['*'], ['ruleInfo']);
                foreach ($data['list'] as $item) {
                    $item['log_time_str'] = date('Y-m-d H:i:s', $item['log_time']);
                    $item['clock_in_time_str'] = Attendance::timeToStr($item['ruleInfo']['clock_in_time']);
                    $item['clock_out_time_str'] = Attendance::timeToStr($item['ruleInfo']['clock_out_time']);
                    $item['check_in_type_str'] = AttendanceLog::getCheckInType($item['check_in_type']);
                    $item['created_at_str'] = date('Y-m-d H:i:s', $item['created_at']->timestamp);
                    unset($item['ruleInfo']);
                }
                break;
            default:
                $data = $log->logList($where, $paging);
        }
        return $data;
    }

    public function factorListPage()
    {
        $data = request(['oa_contacts_id', 'start_time', 'end_time', 'type']);
        switch ($data['type']) {
            case 'leave':
                $rows = [
                    'type' => [
                        'name' => '类型',
                        'length' => 25
                    ],
                    'reasons' => [
                        'name' => '理由',
                        'length' => 100
                    ]
                ];
                break;
            case 'business_trip':
                $rows = [
                    'destination' => [
                        'name' => '目的地',
                        'length' => 25
                    ],
                    'reasons' => [
                        'name' => '理由',
                        'length' => 100
                    ]
                ];
                break;
            case 'overtime':
                $rows = [
                    'workplace' => [
                        'name' => '工作地点',
                        'length' => 25
                    ],
                    'work_content' => [
                        'name' => '工作内容',
                        'length' => 100
                    ]
                ];
                break;
            default:
                xThrow(ERR_PARAMETER);
                return;
        }
        $data['row_list'] = $rows;
        return $this->view('factor-list', $data);
    }

    public function factorList()
    {
        $type = request('type');
        $where = request([
            'oa_contacts_id', 'start_time', 'end_time'
        ]);
        $paging = $this->getPagingRequestParameters();
        $log = new AttendanceFactor();
        switch ($type) {
            case 'leave':
                $stat = Leave::with([]);
                break;
            case 'business_trip':
                $stat = BusinessTrip::with([]);
                break;
            case 'overtime':
                $stat = Overtime::with([]);
                break;
            default:
                xThrow(ERR_PARAMETER);
                return;
        }
        $data = $log->commonList($stat, $where, $paging);
        foreach ($data['list'] as $item) {
            $item['start_time_str'] = date('Y-m-d H:i:s', $item['start_time']);
            $item['end_time_str'] = date('Y-m-d H:i:s', $item['end_time']);
            switch ($type) {
                case 'leave':
                    $item['type_str'] = Flow::getLeaveTypeStr($item['type']);
                    break;
                case 'business_trip':
                    // nothing
                    break;
                case 'overtime':
                    // nothing
                    break;
            }
        }
        return $data;
    }

    public function ruleSetUpPage()
    {
        $dpIds = request('department_ids');
        $name = request('name');
        $data = [];
        if (!empty($dpIds)) {
            $manager = new Attendance();
            try {
                $data = $manager->ruleCheck($dpIds);
                $data['department_ids'] = $dpIds;
                $data['name'] = $name;
            } catch (\DebugError $e) {
                return $this->ajaxFail($e->getMessage());
            }
        }
        return $this->view('rule-set-up', $data);
    }

    public function ruleSetUp()
    {
        $companyId = session('current_operation_company_id');
        if (!$companyId) xThrow(ERR_CURRENT_OPERATION_COMPANY_ID_NOT_EXIST);
        $params = $this->getRequestParameters([
            'department_ids', 'is_apply_to_sub_dp', 'clock_in_time', 'clock_out_time', 'absence_time',
            'clock_in_last_time', 'clock_out_last_time', 'is_sat_workday', 'clock_in_start_time', 'check_in_distance'
        ], [
            'exception_dates_work', 'exception_dates_not_work'
        ]);
        if ($params['department_ids'] === 0 || $params['department_ids'] === '0') xThrow(ERR_PARAMETER, '请选部门');
        if (empty($params['exception_dates_work'])) $params['exception_dates_work'] = [];
        if (empty($params['exception_dates_not_work'])) $params['exception_dates_not_work'] = [];
        $manager = new Attendance();
        try {
            $manager->ruleSetUp(
                $companyId, $params['department_ids'], $params['check_in_distance'],
                $params['clock_in_start_time'], $params['clock_in_time'],
                $params['clock_out_time'], $params['absence_time'],
                $params['clock_in_last_time'], $params['clock_out_last_time'],
                $params['is_sat_workday'], $params['is_apply_to_sub_dp'], $params['exception_dates_work'],
                $params['exception_dates_not_work']
            );
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->ajaxSuccess();
    }

    public function ruleCheck()
    {
        $params = $this->getRequestParameters(['department_ids']);
        $manager = new Attendance();
        try {
            $data = $manager->ruleCheck($params['department_ids']);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $data;
    }

    public function deleteExceptionDate()
    {
        $params = $this->getRequestParameters(['ids']);
        $manager = new Attendance();
        try {
            $data = $manager->deleteExceptionDate($params['ids']);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        return $this->ajaxSuccess('删除成功');
    }
}